<?php
  require '../../include/library.inc.php';
  require '../../include/admin_login.inc.php';
    
  $image_id = intval($_GET['image_id']);
  $project_id = intval($_GET['project_id']);
  $direction_check = intval($_GET['direction']);
  $top = intval($_GET['top']);
  
  if($image_id && ($direction_check == 1 || $direction_check == -1)) {
  	
  	# Get the current order number
  	$sql = "SELECT 
              order_number
            FROM
              project_gallery
            WHERE
              id = ".$image_id."
			";
  	$result = query($sql);
    $row = mysql_fetch_assoc($result);
    $old_order_number = $row['order_number'];
    
    # Get the ID of replaced element
  	$sql = "SELECT
  	           id
  	        FROM
  	           project_gallery
  	        WHERE
  	           order_number = ".$old_order_number." + (".$_GET['direction'].")
  	         ";
  	$result = query($sql);
  	$row = mysql_fetch_assoc($result);
  	$replaced_image_id = $row['id'];
  	 
  	# Move current element one position
    $sql = "UPDATE 
               project_gallery
            SET
              order_number = order_number + (".$_GET['direction'].") 
            WHERE
               id = '".$image_id."' 
             ";
    query($sql);
    
    # Move replaced element to currect element's place
    # Update order of replaced element
    $sql = "UPDATE 
               project_gallery
            SET
              order_number = ".$old_order_number." 
            WHERE
               id = '".$replaced_image_id."'
             ";
    query($sql);
    
  } elseif ($image_id && $top==1) {
	  
	$sql = 'SELECT MAX(order_number) AS max_order_number FROM project_gallery WHERE project_id = $project_id ';
	$row = mysql_fetch_assoc(query($sql));
	$max_order_number = $row['max_order_number'];
	  
	$sql = "SELECT
			  order_number
			FROM
			  project_gallery
			WHERE
			  id = '$image_id'
              ";
    query($sql);
	$row = mysql_fetch_assoc(query($sql));
	$order_number = $row['order_number'];
	
	$sql = "UPDATE
              project_gallery
            SET
              order_number = order_number - 1
            WHERE
              order_number > '$order_number'
			  
			  AND project_id = $project_id 
              ";
    query($sql);
	
	$sql = "UPDATE
              project_gallery
            SET
              order_number = $max_order_number
            WHERE
              id = '$image_id'
              ";
    query($sql);
	  
  }
  
  redirect($_SERVER['HTTP_REFERER']."#gallery");
?>